Telegram Group & Telegram Channel
Скрытые фичи Enum: как выжать максимум

Многие используют Enum как простой список констант. Но у enum.Enum в Python есть куда больше возможностей — и они могут сделать код чище и мощнее.


Вот несколько приёмов, которые мало кто использует — но зря.


1. Добавление поведения в Enum


from enum import Enum

class Status(Enum):
DRAFT = 'draft'
PUBLISHED = 'published'
ARCHIVED = 'archived'

def is_visible(self):
return self in {Status.DRAFT, Status.PUBLISHED}


Теперь Status.DRAFT.is_visible() — это просто и элегантно.


2. Enum с полями


from enum import Enum

class Color(Enum):
RED = ('#FF0000', 'danger')
GREEN = ('#00FF00', 'safe')

def __init__(self, hex_code, label):
self.hex_code = hex_code
self.label = label



Color.RED.hex_code # '#FF0000'
Color.RED.label # 'danger'



3. Автоматические значения с auto()


from enum import Enum, auto

class Role(Enum):
ADMIN = auto()
USER = auto()
GUEST = auto()


Удобно, если не важны конкретные значения, а нужны уникальные.


4. Строгая сериализация

В реальных приложениях (API, базы) лучше контролировать сериализацию enum'ов:


import json

class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Enum):
return obj.value
return super().default(obj)

json.dumps(Status.PUBLISHED, cls=CustomEncoder) # "published"



5. Сравнение по значению


Status('draft') == Status.DRAFT # True
Status('draft') is Status.DRAFT # True (enum гарантирует singleton)


Итого: Enum — это не просто константы. Это лёгкий способ инкапсулировать поведение и данные, улучшить читаемость и сделать код устойчивее к ошибкам.

👉@BookPython



tg-me.com/BookPython/3623
Create:
Last Update:

Скрытые фичи Enum: как выжать максимум

Многие используют Enum как простой список констант. Но у enum.Enum в Python есть куда больше возможностей — и они могут сделать код чище и мощнее.


Вот несколько приёмов, которые мало кто использует — но зря.


1. Добавление поведения в Enum


from enum import Enum

class Status(Enum):
DRAFT = 'draft'
PUBLISHED = 'published'
ARCHIVED = 'archived'

def is_visible(self):
return self in {Status.DRAFT, Status.PUBLISHED}


Теперь Status.DRAFT.is_visible() — это просто и элегантно.


2. Enum с полями


from enum import Enum

class Color(Enum):
RED = ('#FF0000', 'danger')
GREEN = ('#00FF00', 'safe')

def __init__(self, hex_code, label):
self.hex_code = hex_code
self.label = label



Color.RED.hex_code # '#FF0000'
Color.RED.label # 'danger'



3. Автоматические значения с auto()


from enum import Enum, auto

class Role(Enum):
ADMIN = auto()
USER = auto()
GUEST = auto()


Удобно, если не важны конкретные значения, а нужны уникальные.


4. Строгая сериализация

В реальных приложениях (API, базы) лучше контролировать сериализацию enum'ов:


import json

class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Enum):
return obj.value
return super().default(obj)

json.dumps(Status.PUBLISHED, cls=CustomEncoder) # "published"



5. Сравнение по значению


Status('draft') == Status.DRAFT # True
Status('draft') is Status.DRAFT # True (enum гарантирует singleton)


Итого: Enum — это не просто константы. Это лёгкий способ инкапсулировать поведение и данные, улучшить читаемость и сделать код устойчивее к ошибкам.

👉@BookPython

BY Библиотека Python разработчика | Книги по питону


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/BookPython/3623

View MORE
Open in Telegram


Библиотека Python разработчика | Книги по питону Telegram | DID YOU KNOW?

Date: |

That strategy is the acquisition of a value-priced company by a growth company. Using the growth company's higher-priced stock for the acquisition can produce outsized revenue and earnings growth. Even better is the use of cash, particularly in a growth period when financial aggressiveness is accepted and even positively viewed.he key public rationale behind this strategy is synergy - the 1+1=3 view. In many cases, synergy does occur and is valuable. However, in other cases, particularly as the strategy gains popularity, it doesn't. Joining two different organizations, workforces and cultures is a challenge. Simply putting two separate organizations together necessarily creates disruptions and conflicts that can undermine both operations.

To pay the bills, Mr. Durov is issuing investors $1 billion to $1.5 billion of company debt, with the promise of discounted equity if the company eventually goes public, the people briefed on the plans said. He has also announced plans to start selling ads in public Telegram channels as soon as later this year, as well as offering other premium services for businesses and users.

Библиотека Python разработчика | Книги по питону from hk


Telegram Библиотека Python разработчика | Книги по питону
FROM USA